package org.foj.action;

import org.appfuse.webapp.action.BaseAction;
import org.foj.model.Comment;
import org.foj.model.Issue;
import org.foj.service.CommentManager;
import org.foj.service.IssueManager;

import java.util.Date;
import java.util.List;

/**
 * @author jeremy anderson
 */
public class CommentAction extends BaseAction {

    private CommentManager commentManager;
    private IssueManager issueManager;
    private List<Comment> comments;
    private Comment comment;
    private Long id;
    private Long issueId;
    private Issue issue;

    public void setCommentManager(CommentManager commentManager) {
        this.commentManager = commentManager;
    }

    public void setIssueManager(IssueManager issueManager) {
        this.issueManager = issueManager;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setIssueId(Long issueId) {
        this.issueId = issueId;
    }

    public Long getIssueId() {
        return issueId;
    }

    public Issue getIssue() {
        return issue;
    }

    public void setIssue(Issue issue) {
        this.issue = issue;
    }

    public Comment getComment() {
        return comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }

    public List<Comment> getComments() {
        return comments;
    }

    public String list() {
        comments = commentManager.getAll();
        return SUCCESS;
    }

    public String delete() {
        commentManager.remove(comment.getId());
        saveMessage(getText("comment.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            comment = commentManager.get(id);
            issue = comment.getIssue();
        } else {
            comment = new Comment();
            comment.setCreatedDate(new Date());
        }
        
        return SUCCESS;
    }

    public String save() {
        if (cancel != null) {
            return CANCEL;
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (comment.getId() == null);

        if (issue != null && issue.getId() != null) {
            issue = issueManager.get(issue.getId());
            comment.setIssue(issue);
        } 

        comment = commentManager.save(comment);

        String key = isNew ? "comment.added" : "comment.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }

}
